<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class OrderItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'order_id',
        'product_id',
        'variant_id',
        'sku',
        'product_name',
        'variant_name',
        'specifications',
        'price',
        'quantity',
        'total_amount',
        'discount_amount',
        'tax_amount',
        'notes',
        'status',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'total_amount' => 'decimal:2',
        'discount_amount' => 'decimal:2',
        'tax_amount' => 'decimal:2',
        'specifications' => 'array',
    ];

    /**
     * 追加到模型数组表单的访问器
     */
    protected $appends = [
        'subtotal',
        'product_specs',
        'product_image',
    ];

    /**
     * 关联订单
     */
    public function order(): BelongsTo
    {
        return $this->belongsTo(Order::class);
    }

    /**
     * 关联产品
     */
    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    /**
     * 关联变体
     */
    public function variant(): BelongsTo
    {
        return $this->belongsTo(ProductVariant::class);
    }

    /**
     * 获取完整的产品名称
     */
    public function getFullProductNameAttribute(): string
    {
        if ($this->variant_name) {
            return $this->product_name . ' ' . $this->variant_name;
        }
        return $this->product_name;
    }

    /**
     * 判断是否为多规格产品
     */
    public function isMultiVariant(): bool
    {
        return !is_null($this->variant_id);
    }

    /**
     * 判断是否为单规格产品
     */
    public function isSingleVariant(): bool
    {
        return is_null($this->variant_id);
    }

    /**
     * 获取规格信息
     */
    public function getSpecificationsAttribute($value)
    {
        if ($value) {
            return is_string($value) ? json_decode($value, true) : $value;
        }
        
        // 如果冗余存储为空，从关联表获取
        if ($this->isMultiVariant() && $this->variant) {
            return $this->variant->attributes;
        } elseif ($this->product) {
            return $this->product->specifications;
        }
        
        return [];
    }

    /**
     * 获取 subtotal 访问器（兼容前端）
     */
    public function getSubtotalAttribute()
    {
        return $this->total_amount;
    }

    /**
     * 获取 product_specs 访问器（兼容前端）
     */
    public function getProductSpecsAttribute()
    {
        $specs = $this->specifications ?? [];
        
        // 确保返回的是数组格式的规格信息
        if (is_array($specs) && !empty($specs)) {
            // 如果规格是对象数组，转换为前端期望的格式
            if (isset($specs[0]) && is_array($specs[0]) && isset($specs[0]['name']) && isset($specs[0]['value'])) {
                return $specs;
            }
        }
        
        // 对于单规格商品或没有规格的商品，返回空数组
        return [];
    }

    /**
     * 获取 product_image 访问器（兼容前端）
     */
    public function getProductImageAttribute()
    {
        // 优先从变体获取图片
        if ($this->variant && $this->variant->relationLoaded('images') && $this->variant->images->isNotEmpty()) {
            return $this->variant->images->first()->image_path;
        }
        
        // 从产品获取图片
        if ($this->product && $this->product->relationLoaded('images') && $this->product->images->isNotEmpty()) {
            return $this->product->images->first()->image_path;
        }
        
        // 返回占位图
        return '/images/placeholder.jpg';
    }

    /**
     * 计算小计金额
     */
    public function calculateTotalAmount(): void
    {
        $this->total_amount = $this->price * $this->quantity;
    }

    /**
     * 作用域：按状态筛选
     */
    public function scopeByStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    /**
     * 作用域：多规格产品
     */
    public function scopeMultiVariant($query)
    {
        return $query->whereNotNull('variant_id');
    }

    /**
     * 作用域：单规格产品
     */
    public function scopeSingleVariant($query)
    {
        return $query->whereNull('variant_id');
    }
}
